package cli

import (
	"encoding/json"
	"flag"
	"os"
	"strconv"
	"strings"
	"x1aCron/internal/utils"
)

var (
	start   = flag.Bool("start", false, "启动守护进程")
	add     = flag.String("add", "", "添加任务: interval:command (例: 30s:echo hello)")
	list    = flag.Bool("list", false, "列出所有任务")
	remove  = flag.Int64("remove", -1, "删除指定ID的任务")
	stop    = flag.Bool("stop", false, "停止")
	status  = flag.Bool("status", false, "查看状态")
	support = flag.Bool("support", false, "查看支持的任务")
)

func ParseArgs() {
	flag.Parse()

	if flag.NFlag() == 0 {
		flag.Usage()
		os.Exit(1)
	}
}

func GetStart() bool {
	return *start
}

// GetAdd 返回add参数值
func GetAdd() string {
	return *add
}

// GetList 返回list参数值
func GetList() bool {
	return *list
}

// GetRemove 返回remove参数值
func GetRemove() int64 {
	return *remove
}

// GetStop 返回stop参数值
func GetStop() bool {
	return *stop
}

// GetStatus 返回status参数值
func GetStatus() bool {
	return *status
}

func GetSupport() bool {
	return *support
}

func GenerateTasks() json.RawMessage {
	// 生成请求列表
	requests := &utils.Requests{
		Requests: []utils.Request{},
	}

	// 任务添加
	if GetAdd() != "" {
		slice := strings.Fields(GetAdd())
		if len(slice) != 3 {
			panic("Invalid add format, expected: interval:actionType:actionData")
		}
		interval, err := strconv.Atoi(slice[0])
		if err != nil {
			panic("Invalid interval format: " + slice[0])
		}
		data, err := json.Marshal(utils.AddTaskData{
			Interval:   int64(interval),
			ActionType: slice[1],
			ActionData: slice[2],
		})
		if err != nil {
			panic("Failed to marshal remove task data: " + err.Error())
		}
		request := utils.Request{
			TaskType: utils.AddTask,
			Data:     data,
		}
		requests.Requests = append(requests.Requests, request)
	}

	// 任务删除
	if GetRemove() != -1 {
		data, err := json.Marshal(utils.RemoveTaskData{ID: GetRemove()})
		if err != nil {
			panic("Failed to marshal remove task data: " + err.Error())
		}
		request := utils.Request{
			TaskType: utils.Remove,
			Data:     data,
		}
		requests.Requests = append(requests.Requests, request)
	}

	// 任务列表
	if GetList() {
		request := utils.Request{
			TaskType: utils.List,
			Data:     nil,
		}
		requests.Requests = append(requests.Requests, request)
	}

	// 停止
	if GetStop() {
		request := utils.Request{
			TaskType: utils.Stop,
			Data:     nil,
		}
		requests.Requests = append(requests.Requests, request)
	}

	// 状态
	if GetStatus() {
		request := utils.Request{
			TaskType: utils.Status,
			Data:     nil,
		}
		requests.Requests = append(requests.Requests, request)
	}

	if GetSupport() {
		request := utils.Request{
			TaskType: utils.Support,
			Data:     nil,
		}
		requests.Requests = append(requests.Requests, request)
	}

	data, err := json.Marshal(requests)
	if err != nil {
		panic("Failed to marshal requests: " + err.Error())
	}
	return data
}
